package com.carson.undergo.utils;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;

import com.model.common.utils.always.ToastUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Create by Carson on 2022/6/15.
 */
public class ImageUtils {

    public static void saveImageToGallery(Context context, Bitmap bmp) {
        // 首先保存图片
        File appDir = new File(Environment.getExternalStorageDirectory() + File.separator
                + Environment.DIRECTORY_DCIM + File.separator + "signPic");
        if (!appDir.exists()) {
            Log.e("保存Bitmap", "去创建文件夹");
            appDir.mkdirs();
        }
        String fileName = "sign_" + System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        try {
            Log.e("保存Bitmap", "开始保存图片");
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
            // 最后通知图库更新
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
            ToastUtils.showMessage(context, "图片保存成功 ");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            Log.e("保存Bitmap", "保存图片失败:" + e.toString());
            ToastUtils.showMessage(context, "图片保存失败");
        } catch (IOException e) {
            e.printStackTrace();
            Log.e("保存Bitmap", "保存图片失败:" + e.toString());
            ToastUtils.showMessage(context, "图片保存失败");
        }
    }
}
